package com.example.springsecurity.service;

import com.example.springsecurity.mapper.UserMapper;
import com.example.springsecurity.pojo.MyUser;
import com.example.springsecurity.pojo.MyUserDetails;
import com.example.springsecurity.pojo.Result;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsManager {
    //userservice只有一个方法，即loadUserByUsername，该方法返回的是MyUserDetails，
    //而userdetailsmanager有更多方法如:
    // createUser***，updateUser，deleteUser，changePassword，userExists

    //UserDetailsPasswordService接口用来自动升级密码(对数据库中的密码进行加密)，这一操作基于认证成功后

    @Resource
    private UserMapper userMapper;

    @Override
    public void createUser(UserDetails userDetails) {
        MyUser myUser=new MyUser();

        //在service层加密，而不是在controller层加密
        String password = userDetails.getPassword();
        String encodePassword = "{bcrypt}"+new BCryptPasswordEncoder().encode(password);
        //这个并不会自动加前缀，要手动加

        myUser.setUsername(userDetails.getUsername());
        myUser.setPassword(encodePassword);
        userMapper.insertUser(myUser);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = userMapper.getUserByUsername(username);
        if (myUser == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        MyUserDetails myUserDetails = new MyUserDetails(myUser);
        return myUserDetails;//自定义的controller层没有调用该UserDetailsServiceImpl，而是框架自动调用了该层
        //实现了接口的类一般都是框架自动调用的
    }




    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }


}
